package com.itgacl.magic4j.libcommon.component.license.controller;

import cn.hutool.core.util.StrUtil;
import com.itgacl.magic4j.libcommon.bean.R;
import com.itgacl.magic4j.libcommon.component.license.bean.LicenseInfo;
import com.itgacl.magic4j.libcommon.component.license.dto.LicenseCheckDTO;
import com.itgacl.magic4j.libcommon.component.license.dto.LicenseDTO;
import com.itgacl.magic4j.libcommon.component.license.service.LicenseService;
import com.itgacl.magic4j.libcommon.component.license.vo.LicenseCheckResultVo;
import com.itgacl.magic4j.libcommon.component.license.vo.LicenseVo;
import com.itgacl.magic4j.libcommon.component.storage.StorageFactory;
import com.itgacl.magic4j.libcommon.component.storage.bean.UploadResult;
import com.itgacl.magic4j.libcommon.exception.Magic4jException;
import com.itgacl.magic4j.libcommon.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author gacl
 * @version 1.0
 * @description: License服务接口
 * @date 2021/12/24 14:06
 */
@Slf4j
@RequestMapping("/api/license")
@RestController
@Api(tags = "License服务接口")
public class LicenseController {

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private LicenseService licenseService;

    /**
     * 根据文件所在路径下载文件
     * @param filePath
     */
    private void download(String filePath){
        File file = new File(filePath);
        // 取得文件名。
        String fileName = file.getName();
        InputStream fis;
        try {
            fis = new FileInputStream(file);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Length", String.valueOf(file.length()));

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            response.flushBuffer();
            fis.close();
        }catch (IOException e) {
            log.error("license文件下载失败",e);
            throw new RuntimeException(e);
        }
    }

    @ApiOperation("解析证书内容")
    @PostMapping("/decode")
    public R<LicenseVo> decode(@RequestParam("licenseFile") MultipartFile file) throws Exception {
        return R.ok(licenseService.decode(file));
    }

    @ApiOperation("创建并下载授权证书")
    @PostMapping(value = "/create",produces = MediaType.APPLICATION_JSON_VALUE)
    public void create(@RequestBody LicenseDTO licenseDTO){
        try {
            LicenseInfo licenseInfo = licenseService.create(licenseDTO);
            if(licenseInfo!=null){
                if(StrUtil.isNotBlank(licenseInfo.getLicenseFilePath())){
                    download(licenseInfo.getLicenseFilePath());
                    //删除本地文件
                    FileUtil.delete(licenseInfo.getLicenseFilePath());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Magic4jException("License证书生成出错，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation("创建授权证书")
    @PostMapping(value = "/createLicense",produces = MediaType.APPLICATION_JSON_VALUE)
    public R<String> createLicense(@Validated @RequestBody LicenseDTO licenseDTO){
        String licenseFileUrl="";
        try {
            LicenseInfo licenseInfo = licenseService.create(licenseDTO);
            if(licenseInfo!=null){
                if(StrUtil.isNotBlank(licenseInfo.getLicenseFilePath())){
                    //上传license证书到文件服务器
                    UploadResult uploadResult = StorageFactory.build().uploadFile(licenseInfo.getLicenseFilePath());
                    if(uploadResult.isUploadSuccess()){
                        licenseFileUrl = uploadResult.getFileUrl();
                        //删除本地文件
                        FileUtil.delete(licenseInfo.getLicenseFilePath());
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Magic4jException("License证书生成出错，错误信息：" + e.getMessage());
        }
        return R.ok(licenseFileUrl);
    }

    @ApiOperation("校验License")
    @PostMapping(value = "/check")
    public R<LicenseCheckResultVo> check(@Validated @RequestBody LicenseCheckDTO licenseCheckDTO){
       return R.ok(licenseService.licenseCheck(licenseCheckDTO));
    }
}
